import 'package:flutter_provider_demo/data/models/cart.dart';
import 'package:sqflite/sqflite.dart';

class CartRepository {
  CartRepository({
    required Database database,
  }) : _db = database;

  late final Database _db;

  Future<int> add(CartModel cart) async {
    return await _db.insert('cart', cart.toMap());
  }

  Future<CartModel?> getByCatalogId(int catalogId) async {
    final List<Map<String, dynamic>> maps = await _db.query('cart', where: 'catalog_id = ?', whereArgs: [catalogId]);
    if (maps.isNotEmpty) {
      return CartModel.fromMap(maps.first);
    }
    return null;
  }

  Future<List<CartModel>> getAll() async {
    final List<Map<String, dynamic>> maps = await _db.query('cart');
    return List.generate(maps.length, (i) => CartModel.fromMap(maps[i]));
  }

  Future<int> deleteByCatalogId(int catalogId) async {
    return await _db.delete('cart', where: 'catalog_id = ?', whereArgs: [catalogId]);
  }

  Future<int> clear() async {
    return await _db.delete('cart');
  }
}
